package org.gdsdxy.pmmp.web.action;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.gdsdxy.pmmp.entity.MemberBaseInfo;
import org.gdsdxy.pmmp.entity.MemberImge;
import org.gdsdxy.pmmp.service.IUserManagerService;
import org.gdsdxy.pmmp.web.form.ImgeForm;

public class ImgeUploadAction extends Action {
  private IUserManagerService service;

  public void setService(IUserManagerService service) {
    this.service = service;
  }

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// TODO Auto-generated method stub
		ImgeForm imgeForm=(ImgeForm)form;
		//struts���ϴ��ļ��ķ�װ
		FormFile file=imgeForm.getImge();
		String fileName=file.getFileName();
		MemberImge imge=new MemberImge();
		String forward="fail";
		//String dir="D:\\ccx\\jdk\\workspace\\pmmp\\WebRoot\\uploadimge\\";
		//String dir="E:\\apache-tomcat-6.0.20\\webapps\\pmmp\\uploadimge\\";
		//�����·�����Ż�
		String path = req.getContextPath();
		String dir = req.getRealPath("uploadimge")+"\\";
		HttpSession session = req.getSession();
		MemberBaseInfo baseInfo=(MemberBaseInfo)session.getAttribute("member");
		
		try{
			InputStream input=file.getInputStream();
			
			/*imge.setImge(Hibernate.createBlob(input));
			imge.setIsHead("0");//0-����ͷ��
			boolean isSeccuss=service.addMemberImge(imge);
			
			if(isSeccuss){
				forward="success";
			}*/
			imge.setIsHead("0");//0-����ͷ��
			imge.setImg(fileName);
			imge.setBaseInfo(baseInfo);
			boolean isSeccuss=service.addMemberImge(imge);
			//boolean isSeccuss=service.addMemberImge(imge);
			//boolean isSeccuss=true;
			if(isSeccuss){
				OutputStream out =new FileOutputStream(dir+fileName);
				byte[] content =new byte[file.getFileSize()];
				while(input.read(content)!=-1){
					out.write(content);
				}
				out.flush();
				out.close();
				forward="success";
				req.setAttribute("url", "/pmmp/user/memberImgeFy.do?method=query");
				req.setAttribute("msg", "���ͼƬ�ɹ�");
			}
		}catch(IOException e){
			e.printStackTrace();
			mapping.findForward("fail");
		}
		
		return mapping.findForward(forward);
	}

}
